package com.shexianyu.notes.web.service.impl;

import com.shexianyu.notes.web.dao.SysUserRepository;
import com.shexianyu.notes.web.entity.SysUser;
import com.shexianyu.notes.web.service.SysUserService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author sxy
 * @version 1.0
 * @date 2021/2/26 14:25
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    private final SysUserRepository userRepository;

    public SysUserServiceImpl(SysUserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public SysUser findByAccount(String account) {
        return userRepository.findByAccount(account);
    }

    //12小时后失效
    private final static int EXPIRE = 12;

    @Override
    public String createToken(SysUser user) {
        //用UUID生成token
        String token = UUID.randomUUID().toString();
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        //过期时间
        LocalDateTime expireTime = now.plusHours(EXPIRE);
        //保存到数据库
        user.setLoginTime(now);
        user.setExpireTime(expireTime);
        user.setToken(token);
        userRepository.save(user);
        return token;
    }

    @Override
    public void logout(String token) {
        SysUser user = userRepository.findByToken(token);
        //用UUID生成token
        token = UUID.randomUUID().toString();
        //修改用户的token使原本的token失效，前端需配合将token清除
        user.setToken(token);
        userRepository.save(user);

    }

    @Override
    public SysUser findByToken(String token) {
        return userRepository.findByToken(token);
    }

    @Override
    public void createSysUse(SysUser user) {
        userRepository.save(user);
    }

}
